//
//  UITextView+Emoticon.swift
//  模拟键盘
//
//  Created by apple on 15/12/19.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
/**

代码复核  对重构完成的代码进行检查
1 修改注释
2 确认是否需要进一步重构
3 再一次检查返回值和参数
*/

extension UITextView {
    ///图片表情完整字符串内容
    var emoticonText: String {
    
        
        let attrText = attributedText
        
        var strM = String()
        
        //遍历属性文本
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                print("图片 \(attachment.emoticon)")
                
                strM += attachment.emoticon.chs ?? ""
            } else {
                let str = (attrText.string as NSString).substringWithRange(range)
                
                strM += str
            }
        }
        
//        print("最终结果 \(strM)")
        return strM

    }
    
    ///插入表情符号
    func insertEmoticon(em: Emoticon) {
    
        
        //1 空白表情
        if em.isEmpty {
            
            return
        }
        //2 删除按钮
        if em.isRemoved {
            
            deleteBackward()
            return
        }
        //3 emoji
        if let emoji = em.emoji {
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        //4 图片表情
        insertImageEmoticon(em)
        //5 通知代理文本放生了变化
        delegate?.textViewDidChange?(self)
    
    }
    
    ///插入图片表情
    private func insertImageEmoticon(em: Emoticon) {
        
        // 1 图片的文本属性
        let attachment = EmoticonAttachment(emoticon: em)
        
        attachment.image = UIImage(contentsOfFile: em.imagePath)
        //线高表示字体的高度
        let lineHeight = font!.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
        //获得图片文本
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        //添加字体
        imageText.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
        
        //2 记录 textview attributestring  转换成可变文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        //3 插入图片文本
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        //4 替换属性文本
        //1 记录光标位置
        let range = selectedRange
        //2 替换文本
        attributedText = strM
        //3 恢复光标
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }

    
    
}